package com.cheyunkeji.er.http;

import android.util.Log;

import java.io.IOException;
import okio.Buffer;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author Michael
 * @date 2018/7/18 - 16:18.
 */

public class LogInterceptor implements Interceptor {

    public static String TAG = "LogInterceptor";

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        String postBodyString = "";
        postBodyString = bodyToString(request.body());
        postBodyString += (postBodyString.isEmpty()?"":"&" );
        com.orhanobut.logger.Logger.d("发送请求\nmethod：%s\nurl:%s\n参数:%s", request.method(), request.url(), postBodyString);

        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration=endTime-startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
//        Log.d(TAG,"\n");
//        Log.d(TAG,"----------Start----------------");
//        Log.d(TAG, "| "+request.toString());
//        String method=request.method();
//        if("POST".equals(method)){
//            StringBuilder sb = new StringBuilder();
//            if (request.body() instanceof FormBody) {
//                FormBody body = (FormBody) request.body();
//                for (int i = 0; i < body.size(); i++) {
//                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
//                }
//                sb.delete(sb.length() - 1, sb.length());
//                Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");
//            }
//        }


        com.orhanobut.logger.Logger.d("收到响应 %s%s %s毫秒\n请求url:%s\n请求body:%s\n响应body:%s",
                response.code(), response.message(), duration, response.request().url(), postBodyString, content);

        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }

    private String bodyToString(RequestBody request){
        try {
            Buffer buffer = new Buffer();
            if (request != null)
                request.writeTo(buffer);
                else
            return "";
            return buffer.readUtf8();
        } catch (IOException e) {
            return "did not work";
        }
    }

}
